module Kuztuscms
  class PagesController < KuztuscmsController
    append_view_path Kuztuscms::Resolver.instance

    before_filter :authenticate_for_cms!, :except => [:show]
    before_filter :build_articles_list, :only => [:new, :edit, :create, :update]
    before_filter :build_layouts_list, :only => [:new, :edit, :create, :update]

    # GET /pages
    def index
     @pages = Page.all
    end

    def show
      @page = Page.find_by_path(params[:page])
      @page = Page.default.first if params[:page].blank? && @page.blank?

      if @page
        Kuztuscms.article = @page.article
        Kuztuscms.page = @page
        render :layout => "#{Kuztuscms.layout_prefix}#{@page.layout.path}"
      else
        raise ActionController::RoutingError.new('Not Found')
      end
    end

    # GET /pages/new
    def new
      @page = Page.new
    end

    # GET /pages/1/edit
    def edit
      @page = Page.find(params[:id])
    end

    # POST /pages
    def create
      @page = Page.new(params[:page])

      if @page.save
        redirect_to kuztuscms.pages_url, notice: 'Page was successfully created.'
      else
        render action: "new"
      end
    end

    # PUT /pages/1
    def update
      @page = Page.find(params[:id])

      if @page.update_attributes(params[:page])
        redirect_to kuztuscms.pages_url, notice: 'Page was successfully updated.'
      else
        render action: "edit"
      end
    end

    # DELETE /pages/1
    def destroy
      @page = Page.find(params[:id])
      @page.destroy

      redirect_to kuztuscms.pages_url
    end

    private

      def build_layouts_list
        @layouts = Layout.all
      end

      def build_articles_list
        @articles = Article.all
      end
  end
end
